import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

const USER_KEY = "OA_USER_KEY"
const TOKEN_KEY = "OA_TOKEN_KEY"

export const PermissionChoices = {

    // 普通权限
    Normal: 1,
    // Leader
    Leader: 2,
    // 需要董事会权限
    highest: 3,
}

export const useAuthStore = defineStore('auth', () => {
    let _user = ref({})
    let _token = ref("")

    function setUserToken(user,token){
        _user.value = user;
        _token.value = token

        localStorage.setItem(USER_KEY, JSON.stringify(user))
        localStorage.setItem(TOKEN_KEY, token)  
    }

    let user = computed(()=>{
        if(Object.keys(_user.value)==0){
            let user_str = localStorage.getItem(USER_KEY)
            if(user_str){
                _user.value = JSON.parse(user_str)
            }
        }
        return _user.value
    })
    let token = computed(()=>{
        let token_str = localStorage.getItem(TOKEN_KEY)
        if(token_str){
            _token.value = token_str
        }
        return _token.value
    })

    let is_logined = computed(()=>{
        if(Object.keys(user.value).length>0 && token.value){
            return true
        }
        return false
    })

    let clearUserToken = () => {
        _user.value = {}
        _token.value = ""
        localStorage.removeItem(USER_KEY)
        localStorage.removeItem(TOKEN_KEY)
    }



    let own_permissions = computed(()=>{
        let _permissions = PermissionChoices.Normal
        if(is_logined.value){
            if(user.value.department.name == '董事会'){
                _permissions = PermissionChoices.highest
            }
            if(user.value.department.Leader_id == user.value.uid){
                _permissions |= PermissionChoices.Leader
            }
        }
        return _permissions
    })
    
    function has_permission(permissions=[]){
        let my_permission = own_permissions.value
        let page_permission = Math.min(...permissions)
        if(my_permission < page_permission){
            return false
        }else{
            return true
        }
    }


    return {setUserToken,user,token,is_logined,clearUserToken,has_permission}
  })


